﻿using System;
using Phoenix.Framework;
using Phoenix.Lifetime;
using Xunit;

namespace Phoenix.Tests
{
    public class ViewModelBaseTests
    {
        [Fact]
        public void transient_helper_causes_property_to_be_saved_to_page_state_on_deactivate()
        {
            // arrange
            var controllerActionContext = PhoenixObjectMother.CreateContext(new ControllerAction("", "", ""));
            var viewModel = new TestViewModel
                                {
                                    SomeProperty = "Test", 
                                    Context = controllerActionContext,
                                    PageState = controllerActionContext.RequestState
                                };

            // act
            viewModel.Deactivated(this, EventArgs.Empty);

            // assert
            Assert.Equal("Test", viewModel.PageState.Load<TransientProperty>(viewModel.GetType().FullName + "." + "SomeProperty").Value);
        }

        [Fact]
        public void transient_helper_causes_property_to_be_restored_from_page_state_on_activated()
        {
            // arrange
            var controllerActionContext = PhoenixObjectMother.CreateContext(new ControllerAction("", "", ""));
            var viewModel = new TestViewModel
            {
                Context = controllerActionContext,
                PageState = controllerActionContext.RequestState
            };
            viewModel.PageState.Save(viewModel.GetType().FullName + "." + "SomeProperty", new TransientProperty{ Value = "Test"});

            // act
            viewModel.Activated(this, EventArgs.Empty);

            // assert
            Assert.Equal("Test", viewModel.SomeProperty);
        }

        private class TestViewModel : ViewModelBase
        {
            public TestViewModel()
            {
                Transient(()=>SomeProperty);
            }

            public string SomeProperty { get; set; }
        }
    }
}